<template>
  <div class="emergency-plan-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="预案名称">
          <el-input
            v-model="queryForm.planName"
            placeholder="请输入预案名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="预案类型">
          <el-select
            v-model="queryForm.planType"
            placeholder="请选择预案类型"
            clearable
            style="width: 150px"
          >
            <el-option label="防洪预案" value="flood-control" />
            <el-option label="抗旱预案" value="drought-control" />
            <el-option label="地震预案" value="earthquake" />
            <el-option label="设备故障" value="equipment-failure" />
            <el-option label="其他预案" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="预案状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择预案状态"
            clearable
            style="width: 120px"
          >
            <el-option label="草稿" value="draft" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="已发布" value="published" />
            <el-option label="已停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <el-button type="primary" @click="handleAdd">新增预案</el-button>
      <el-button
        type="danger"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
      <el-button type="success" @click="handleExport">导出数据</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planCode" label="预案编号" width="120" />
        <el-table-column prop="planName" label="预案名称" width="200" />
        <el-table-column prop="planType" label="预案类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.planType)">
              {{ getTypeText(row.planType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="预案级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本号" width="100" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="reviewer" label="审核人" width="100" />
        <el-table-column prop="status" label="预案状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column prop="publishTime" label="发布时间" width="150" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="success" icon="Promotion" @click="handlePublish(row)">发布</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <EmergencyPlanFormDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-view="isView"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import EmergencyPlanFormDialog from './components/EmergencyPlanFormDialog.vue'

// 查询表单
const queryForm = reactive({
  planName: '',
  planType: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const allData = ref([] as any[])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    'flood-control': 'primary',
    'drought-control': 'warning',
    'earthquake': 'danger',
    'equipment-failure': 'info',
    'other': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    'flood-control': '防洪预案',
    'drought-control': '抗旱预案',
    'earthquake': '地震预案',
    'equipment-failure': '设备故障',
    'other': '其他预案'
  }
  return typeMap[type] || type
}

// 获取级别标签样式
const getLevelTagType = (level: string) => {
  const levelMap = {
    'I': 'danger',
    'II': 'warning',
    'III': 'primary',
    'IV': 'success'
  }
  return levelMap[level] || 'info'
}

// 获取级别文本
const getLevelText = (level: string) => {
  const levelMap = {
    'I': 'I级',
    'II': 'II级',
    'III': 'III级',
    'IV': 'IV级'
  }
  return levelMap[level] || level
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    draft: 'info',
    reviewing: 'warning',
    published: 'success',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    draft: '草稿',
    reviewing: '审核中',
    published: '已发布',
    disabled: '已停用'
  }
  return statusMap[status] || status
}

// 生成伪数据
const randomChoice = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)]
const generateMockData = (count: number) => {
  const types = ['flood-control', 'drought-control', 'earthquake', 'equipment-failure', 'other']
  const levels = ['I', 'II', 'III', 'IV']
  const statuses = ['draft', 'reviewing', 'published', 'disabled']
  const names = ['张三', '李四', '王五', '赵六', '钱七']
  const list = [] as any[]
  for (let i = 0; i < count; i++) {
    const id = i + 1
    const type = randomChoice(types)
    const level = randomChoice(levels)
    const status = randomChoice(statuses)
    const creator = randomChoice(names)
    const reviewer = randomChoice(names)
    const date = new Date(2024, Math.floor(Math.random() * 6) + 1, Math.floor(Math.random() * 28) + 1)
    const createdAt = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(Math.floor(Math.random()*24)).padStart(2,'0')}:${String(Math.floor(Math.random()*60)).padStart(2,'0')}:00`
    const publishAt = status === 'published' ? createdAt : ''
    list.push({
      id,
      planCode: `EP2024${String(id).padStart(3, '0')}`,
      planName: `${getTypeText(type)}${id}号预案`,
      planType: type,
      level,
      version: `V${(Math.random()*2+1).toFixed(1)}`,
      creator,
      reviewer,
      status,
      createTime: createdAt,
      publishTime: publishAt,
      department: '应急管理部',
      phone: '13800138000',
      email: 'demo@example.com',
      scope: '全水库范围',
      objective: '确保水库安全',
      organization: '应急指挥部',
      procedure: '预警-响应-处置-恢复',
      resources: '人员、设备、物资',
      communication: '电话、对讲机、短信',
      training: '每年组织2次演练',
      remark: '定期更新'
    })
  }
  return list
}

// 根据查询与分页应用数据
const applyFiltersAndPaginate = () => {
  const { planName, planType, status } = queryForm
  const filtered = allData.value.filter((item) => {
    const matchName = planName ? item.planName.includes(planName) : true
    const matchType = planType ? item.planType === planType : true
    const matchStatus = status ? item.status === status : true
    return matchName && matchType && matchStatus
  })
  pagination.total = filtered.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  tableData.value = filtered.slice(start, end)
}

// 模拟API - 获取应急预案列表
const fetchEmergencyPlanList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    const count = Math.floor(Math.random() * 41) + 10
    allData.value = generateMockData(count)
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除应急预案
const deleteEmergencyPlan = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    applyFiltersAndPaginate()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 发布预案
const publishEmergencyPlan = async (id: number) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    const idx = allData.value.findIndex(i => i.id === id)
    if (idx !== -1) {
      allData.value[idx].status = 'published'
      allData.value[idx].publishTime = allData.value[idx].createTime
    }
    applyFiltersAndPaginate()
    ElMessage.success('发布成功')
  } catch (error) {
    ElMessage.error('发布失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    planName: '',
    planType: '',
    status: '',
    dateRange: []
  })
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  applyFiltersAndPaginate()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  applyFiltersAndPaginate()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  fetchEmergencyPlanList()
}

// 初始化
onMounted(() => {
  fetchEmergencyPlanList()
})
</script>

<style scoped>
.emergency-plan-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>